function [trl, ERPtype, trialAssign] = ft_trialfun_VAST_ERP(trigs, settings)
%
% Defines trial epochs using the supplied trigger samples. "trigs" should 
% be a struct with fields "enc", "int", and "ret", as created by
% VAST_preproc_ERP. Each of these fields is an array of samples at which
% the indicated trigger occurs.
%
% "reconstruct" (1 or 0) defines whether you're using explicit window
% triggers (41,42,43) or reconstructing start and end samples relative to
% other trigs in the trial.
%
% Outputs a trl array, dictating single-ERP epochs around each event of
% interest.

Ntrl = 240;

if ~isfield(trigs,'enc') || ~isfield(trigs,'int') ||...
        ~isfield(trigs,'ret')
    error("'trigs' is not specified properly. See help for this function.")
end

fs = settings.ds2;
timeBefore = 0.1; % s, amount of time to look BEFORE each trig (baseline) 
timeAfter = 0.5; % s, amount of time to look AFTER each trig

sampsBefore = round(timeBefore * fs);
sampsAfter = round(timeAfter * fs);

% concatenate all the triggers, ignoring type
allTrigs = [trigs.enc.s1, trigs.enc.s2, trigs.enc.s3, trigs.enc.s4,...
            trigs.int.s1, trigs.int.s2, trigs.int.s3,...
            trigs.ret.s1, trigs.ret.s2, trigs.ret.s3, trigs.ret.s4];    

% create a cell array for keeping track of type
ERPtype = cell(size(allTrigs));
typeLabels = {'enc_s1', 'enc_s2', 'enc_s3', 'enc_s4', 'int_s1', 'int_s2',...
              'int_s3', 'ret_s1', 'ret_s2', 'ret_s3', 'ret_s4'};
startInd = 0;
for t = 1:length(typeLabels)
    currtype = typeLabels{t};
    eval(strcat("labelLen = length(trigs.", currtype(1:3), ".",...
                currtype(end-1:end), ");"))
    ERPtype(startInd + 1 : startInd + labelLen) = {currtype};
    startInd = startInd + labelLen;
end

% Sort triggers and ERPtype cell array
[allTrigs, tInd] = sort(allTrigs);
ERPtype = ERPtype(tInd);

% Figure out which trial each ERP belongs to (for condition assignment)
if length(trigs.ret.s4) ~= Ntrl
    error("missing at least one end trial trigger. cannot perform condition assignment.") 
end
trialAssign = zeros(size(allTrigs));
firstSamp = 0;
for t = 1:Ntrl
     lastSamp = trigs.ret.s4(t);
     trialAssign(allTrigs >= firstSamp & allTrigs <= lastSamp) = t;
     firstSamp = lastSamp + 1;
end

% Define trial structure based on sorted triggers
trl = zeros(length(allTrigs), 3);
trl(:,1) = allTrigs - sampsBefore;
trl(:,2) = allTrigs + sampsAfter;

end